package com.wsjj.yjh;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.AllWindowedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.*;

public class ProcessAllWindowTopNDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        env.enableCheckpointing(2000, CheckpointingMode.EXACTLY_ONCE);
        SingleOutputStreamOperator<WaterSensor> stream1 = env.socketTextStream("hadoop102", 7777)
                .map(value -> {
                    String[] split = value.split(",");
                    return new WaterSensor(split[0], Long.valueOf(split[1]), Integer.valueOf(split[2]));
                })
                .assignTimestampsAndWatermarks(WatermarkStrategy.<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                        .withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() {
                            @Override
                            public long extractTimestamp(WaterSensor element, long recordTimestamp) {
                                return element.getTs() * 1000L;
                            }
                        }));
        stream1.print();
        AllWindowedStream<WaterSensor, TimeWindow> windowAll = stream1.windowAll(SlidingEventTimeWindows.of(Time.seconds(10), Time.seconds(5)));
        SingleOutputStreamOperator<String> process = windowAll.process(new MyprocessAll());
        process.print();
        env.execute();

    }
    public static class MyprocessAll extends ProcessAllWindowFunction<WaterSensor,String,TimeWindow>{

        @Override
        public void process(ProcessAllWindowFunction<WaterSensor, String, TimeWindow>.Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {
            Map<Integer, Integer> map = new HashMap<>();
            for (WaterSensor element : elements) {
                Integer vc = element.getVc();
                if(map.containsKey(vc)){
                    map.put(vc,map.get(vc)+1);
                }else {
                    map.put(vc,1);
                }
            }

            List<Tuple2<Integer, Integer>> list = new ArrayList<>();

            for (Integer integer : map.keySet()) {
                list.add(Tuple2.of(integer,map.get(integer)));
            }

            list.sort(new Comparator<Tuple2<Integer, Integer>>() {
                @Override
                public int compare(Tuple2<Integer, Integer> o1, Tuple2<Integer, Integer> o2) {
                    return o2.f1 - o1.f1;
                }
            });

            StringBuffer buffer = new StringBuffer();

            for (int i = 0; i < Math.min(2,list.size()); i++) {
                Tuple2<Integer, Integer> integerIntegerTuple2 = list.get(i);
                String start = DateFormatUtils.format(context.window().getStart(), "yyyy-MM-dd HH:ss:mm");
                String end = DateFormatUtils.format(context.window().getEnd(), "yyyy-MM-dd HH:ss:mm");
                buffer.append("窗口：[" + start + "," + end + ")");
                buffer.append("\n");
                buffer.append("第"+ (i+1) +"名：vc=" +  integerIntegerTuple2.f0 + "  数量：" + integerIntegerTuple2.f1);
                buffer.append("\n");
            }

            out.collect(buffer.toString());

        }


    }

}

